/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bifrost.repository.CountryAreaRepository;
import com.bifrost.entity.CountryArea;
import com.bifrost.common.model.ResultModel;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @author bifrost
 * @version 1.0.0
 * @Date 2017/10/16 15:47
 */
@RestController
@RequestMapping("admin/area")
public class AreaController {

    @Autowired
    CountryAreaRepository countryAreaRepository;
    @Value("${jisu.api.appkey}")
    private String APPKEY;
    @Value("${area.province.api.url}")
    private String PROVINCE_URL;
    @Value("${area.city.api.url}")
    private String CITY_URL;
    @Value("${area.district.api.url}")
    private String DISTRICT_URL;
    @Value("${area.all.api.url}")
    private String ALL_URL;


    @GetMapping("/provinces")
    public ResultModel province() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(String.format("%s?appkey=%s", PROVINCE_URL, APPKEY));
        HttpEntity entity = null;
        try {
            entity = client.execute(httpGet).getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "utf-8");
                JSONObject json = JSON.parseObject(result);
                if (json.getIntValue("status") != 0) {
                    return ResultModel.error(json.getString("msg"));
                } else {
                    JSONArray resultarr = json.getJSONArray("result");
                    for (int i = 0; i < resultarr.size(); i++) {
                        CountryArea countryArea = new CountryArea();
                        JSONObject obj = (JSONObject) resultarr.get(i);
                        countryArea.setName(obj.getString("name"));
                        countryArea.setCode(obj.getString("areacode"));
                        countryArea.setId(obj.getLong("id"));
                        countryArea.setParent(countryAreaRepository.findOne(obj.getLong("parentid")));
                        countryArea.setParentName(obj.getString("parentname"));
                        countryArea.setZipcode(obj.getString("zipcode"));
                        countryArea.setDepth(obj.getIntValue("depth"));
                        countryAreaRepository.save(countryArea);
                    }
                    return ResultModel.ok("成功");
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultModel.error("error");
    }

    @GetMapping("/cities")
    public ResultModel city() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpEntity entity = null;
        try {
            List<CountryArea> areas = countryAreaRepository.findByDepth(1);
            if (areas == null || areas.size() == 0) {
                return ResultModel.error();
            }
            for (CountryArea area : areas) {
                HttpGet httpGet = new HttpGet(String.format("%s?parentid=%s&appkey=%s", CITY_URL, area.getId().toString(), APPKEY));
                entity = client.execute(httpGet).getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, "utf-8");
                    JSONObject json = JSON.parseObject(result);
                    JSONArray resultarr = json.getJSONArray("result");
                    if (resultarr == null || resultarr.size() == 0) {
                        continue;
                    } else {
                        for (int i = 0; i < resultarr.size(); i++) {
                            CountryArea countryArea = new CountryArea();
                            JSONObject obj = (JSONObject) resultarr.get(i);
                            countryArea.setId(obj.getLong("id"));
                            countryArea.setName(obj.getString("name"));
                            countryArea.setCode(obj.getString("areacode"));
                            countryArea.setParent(countryAreaRepository.findOne(obj.getLong("parentid")));
                            countryArea.setParentName(obj.getString("parentname"));
                            countryArea.setZipcode(obj.getString("zipcode"));
                            countryArea.setDepth(obj.getIntValue("depth"));
                            countryAreaRepository.save(countryArea);
                        }
                    }
                }
            }
            return ResultModel.ok("成功!");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultModel.error("error");
    }

    @GetMapping("/districts")
    public ResultModel district() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpEntity entity = null;
        try {
            List<CountryArea> areas = countryAreaRepository.findByDepth(2);
            if (areas == null || areas.size() == 0) return ResultModel.error();
            for (CountryArea area : areas) {
                HttpGet httpGet = new HttpGet(String.format("%s?parentid=%s&appkey=%s", DISTRICT_URL, area.getId().toString(), APPKEY));
                entity = client.execute(httpGet).getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, "utf-8");
                    JSONObject json = JSON.parseObject(result);
                    JSONArray resultarr = json.getJSONArray("result");
                    if (resultarr == null || resultarr.size() == 0) {
                        continue;
                    } else {
                        for (int i = 0; i < resultarr.size(); i++) {
                            CountryArea countryArea = new CountryArea();
                            JSONObject obj = (JSONObject) resultarr.get(i);
                            countryArea.setId(obj.getLong("id"));
                            countryArea.setParent(countryAreaRepository.findOne(obj.getLong("parentid")));
                            countryArea.setName(obj.getString("name"));
                            countryArea.setCode(obj.getString("areacode"));
                            countryArea.setParentName(obj.getString("parentname"));
                            countryArea.setZipcode(obj.getString("zipcode"));
                            countryArea.setDepth(obj.getIntValue("depth"));
                            countryAreaRepository.save(countryArea);
                        }
                    }
                }
            }
            return ResultModel.ok("成功");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultModel.error("error");
    }

    @GetMapping("/all")
    public ResultModel all() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(String.format("%s?appkey=%s", ALL_URL, APPKEY));
        HttpEntity entity = null;
        try {
            entity = client.execute(httpGet).getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "utf-8");
                JSONObject json = JSON.parseObject(result);
                if (json.getIntValue("status") != 0) {
                    return ResultModel.error(json.getString("msg"));
                } else {
                    JSONArray resultarr = json.getJSONArray("result");
                    HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
                    //格式化为小写字母
                    format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
                    //不需要音调
                    format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
                    //设置对拼音字符 ü 的处理
                    format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
                    for (int i = 0; i < resultarr.size(); i++) {
                        CountryArea countryArea = new CountryArea();
                        JSONObject obj = (JSONObject) resultarr.get(i);
                        String name = obj.getString("name");
                        countryArea.setName(name);
                        char[] chars = name.trim().toCharArray();
                        if (chars != null && chars.length > 0) {
                            String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(chars[0], format);
                            if (pinyin != null && pinyin.length > 0) {
                                countryArea.setInitial(StringUtils.left(pinyin[0], 1));
                            }
                        }
                        countryArea.setCode(obj.getString("areacode"));
                        countryArea.setId(obj.getLong("id"));
                        countryArea.setParent(countryAreaRepository.findOne(obj.getLong("parentid")));
                        countryArea.setParentName(obj.getString("parentname"));
                        countryArea.setZipcode(obj.getString("zipcode"));
                        countryArea.setDepth(obj.getIntValue("depth"));
                        countryAreaRepository.save(countryArea);
                    }
                    return ResultModel.ok("成功");
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return ResultModel.error("error");
    }

    /*@GetMapping("/areasByTuhu")
    public String getAllAreas() {
        CloseableHttpClient client = null;
        HttpGet httpGet = new HttpGet(TUHU_AREA_URL);
        HttpEntity entity = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            entity = client.execute(httpGet).getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                JSONObject json = JSON.parseObject(result);
                if (json.getIntValue("Code") != 1) {
                    return "{code:0,msg:\"发生错误\"}";
                } else {

                    JSONArray resultarr = json.getJSONArray("ProviceList");
                    CountryArea privince = null;
                    for (int i = 1; i < resultarr.size(); i++) {
                        JSONObject jsonObject = resultarr.getJSONObject(i);
                        privince = new CountryArea();
                        String provinceName = jsonObject.getString("ProviceName");
                        privince.setName(provinceName);
                        privince.setDepth(1);
                        //Long privinceId =jsonObject.getLong("RegionID");
                        //privince.setId(privinceId);
                        privince.setInitial(getInitial(provinceName));
                        privince = countryAreaRepository.save(privince);
                        CountryArea city = null;
                        JSONArray cityArray = jsonObject.getJSONArray("CityList");
                        for (int j = 0; j < cityArray.size(); j++) {
                            JSONObject cityJson = cityArray.getJSONObject(j);
                            city = new CountryArea();
                            String cityName = cityJson.getString("CtiyName");
                            city.setName(cityName);
                            city.setDepth(2);
                            city.setParent(privince);
                            city.setParentName(provinceName);
                            city.setInitial(getInitial(cityName));
                            //Long cityId = cityJson.getLong("RegionID");
                            //city.setId(cityId);
                            city = countryAreaRepository.save(city);
                            CountryArea district = null;
                            JSONArray areas = cityJson.getJSONArray("AreaList");
                            for (int k = 0; k < areas.size(); k++) {
                                JSONObject area = areas.getJSONObject(k);
                                district = new CountryArea();
                                district.setName(area.getString("CtiyName"));
                                district.setDepth(3);
                                //district.setId(area.getLong("RegionID"));
                                district.setParent(city);
                                district.setParentName(cityName);
                                district.setInitial(getInitial(area.getString("CtiyName")));
                                countryAreaRepository.save(district);
                            }
                        }
                    }
                    return "{code:1,msg:\"成功\"}";
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return "{code:0,msg:\"发生错误\"}";
    }
*/
    private String getInitial(String name) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        //格式化为小写字母
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        //不需要音调
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //设置对拼音字符 ü 的处理
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        char[] chars = name.trim().toCharArray();
        if (chars != null && chars.length > 0) {
            String[] pinyin = new String[0];
            try {
                pinyin = PinyinHelper.toHanyuPinyinStringArray(chars[0], format);
            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                badHanyuPinyinOutputFormatCombination.printStackTrace();
            }
            if (pinyin != null && pinyin.length > 0) {
                return StringUtils.left(pinyin[0], 1);
            }
        }
        return null;
    }
}
